<template>
  <div class="page-dialog">
    <el-dialog v-model="dialogVisible" :title="dialogConfig.title" width="30%" center>
      <Form v-bind="dialogConfig" v-model="formData" />
      <slot></slot>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, defineProps, defineExpose, watch } from 'vue'
import { useStore } from 'vuex'
import Form from '@/base-ui/form'

const props = defineProps({
  dialogConfig: {
    type: Object,
    default: () => ({})
  },
  defaultInfo: {
    type: Object,
    default: () => ({})
  },
  otherInfo: {
    type: Object,
    default: () => ({})
  },
  pageName: {
    type: String,
    default: ''
  }
})

const dialogVisible = ref(false)
const formData = ref<any>({})
// 使用这样监听defaultInfo值变化， Form组件必须要使用直接的双向绑定方式（即@/base-ui/form/index2.vue这个组件）
watch(
  () => props.defaultInfo,
  (newVal) => {
    // console.log('newVal: ', newVal)
    for (const item of props.dialogConfig.formConfig.formItem) {
      formData.value[`${item.field}`] = newVal[`${item.field}`]
    }
  }
)

const store = useStore()
const dialogConfirm = () => {
  dialogVisible.value = false
  if (Object.keys(props.defaultInfo).length) {
    // 编辑
    // console.log('编辑')
    // console.log(props.defaultInfo)
    store.dispatch('system/editPageData', {
      editData: { ...formData.value, ...props.otherInfo },
      pageName: props.pageName,
      id: props.defaultInfo.id
    })
  } else {
    // 新建
    // console.log('新建')
    store.dispatch('system/createPageData', {
      newData: { ...formData, ...props.otherInfo },
      pageName: props.pageName
    })
  }
}

defineExpose({ dialogVisible })
</script>
